package com.ruoyi.common.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * lhp
 * 2023/8/15
 * 生成以日期开头，加4位数字，每次加1的工具类.如：201712140001，第二日再从1开始计算
 */
public class NumberGeneratorUtil {
    private static final DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    private static Date lastDate = null;
    private static int counter = 1;

    //加锁
    public static synchronized String generateNumber() {
        Date currentDate = new Date();
        if (lastDate == null || !isSameDay(currentDate, lastDate)) {
            lastDate = currentDate;
            counter = 1;
        }
        String datePrefix = dateFormat.format(currentDate);
        String numberSuffix = String.format("%04d", counter++);
        return datePrefix + numberSuffix;
    }

    private static boolean isSameDay(Date date1, Date date2) {
        DateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");
        return dayFormat.format(date1).equals(dayFormat.format(date2));
    }
}
